﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql.Internal.Model;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Extension;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;

namespace Bzzb.Controllers
{
    public class GouJianZhuangBeiController : BaseController
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;
        private readonly ILogger<GouJianZhuangBeiController> _logger;
        public GouJianZhuangBeiController(ILogger<GouJianZhuangBeiController> logger, IFreeSql fsql, IConfiguration configuration, IWebHostEnvironment env) : base(fsql)
        {
            this._env = env;
            this._logger = logger;
            this._configuration = configuration;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long bzzbtid, [FromForm] long bzzbid, [FromForm] long jtid, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            long total = 0;
            List<GouJianZhuangBei> goujianzhuangbeis;
            if (doPage == 0)
            {
                goujianzhuangbeis = await _fsql.Select<GouJianZhuangBei>().Where(gjzb => gjzb.Bzzbtid == bzzbtid && gjzb.Bzzbid == bzzbid && gjzb.Jtid == jtid).ToListAsync();
            }
            else {
                goujianzhuangbeis = await _fsql.Select<GouJianZhuangBei>().Where(gjzb => gjzb.Bzzbtid == bzzbtid && gjzb.Bzzbid == bzzbid && gjzb.Jtid == jtid).Count(out total).Page(pageNumber, pageSize).ToListAsync();
                
            }
            _logger.LogInformation("构件装备：" + _fsql.Select<GouJianZhuangBei>().Where(gjzb => gjzb.Bzzbtid == bzzbtid && gjzb.Bzzbid == bzzbid && gjzb.Jtid == jtid).ToSql());
            JObject data = new();
            data.Add("total", total);
            data.Add("list", JArray.FromObject(goujianzhuangbeis));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] GouJianZhuangBei goujianzhuangbei)
        {
            long id = await _fsql.Insert(goujianzhuangbei).ExecuteIdentityAsync();
            goujianzhuangbei.Id = id;

            await _fsql.Update<GouJianZhuangBei>(id).Set(gjzb => gjzb.Gjwybm, goujianzhuangbei.Ssbm + String.Format("{0:D4}", id)).ExecuteAffrowsAsync();

            return RenderJson(data: goujianzhuangbei);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = await _fsql.Delete<GouJianZhuangBei>().Where(gjzb => gjzb.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] GouJianZhuangBei goujianzhuangbei) {
            int affrows = await _fsql.Update<GouJianZhuangBei>().SetSourceIgnore(goujianzhuangbei, colval => colval == null).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            GouJianZhuangBei goujianzhuangbei = await _fsql.Select<GouJianZhuangBei>().Where(gjzb => gjzb.Id == id).ToOneAsync();
            return RenderJson(data: goujianzhuangbei);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> DownloadExcelTemplate()
        {
            IExcelExporter exporter = new ExcelExporter();
            var filePath = @"wwwroot/download/goujian/构件库模板.xlsx";
            var arr = new[] { "构件唯一编码(前缀)", "构件名称", "构件型号", "构件出厂号"/*, "所属编码", "车牌号", "名称"*/ };
            var sheetName = "构件库";
            var result = await exporter.ExportHeaderAsByteArray(arr, sheetName);
            result.ToExcelExportFileInfo(filePath);
            JObject data = new();
            data.Add("url", _configuration.GetValue<string>("UploadUrl") + $"/download/goujian/构件库模板.xlsx");
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> ExportExcel([FromForm] long bzzbtid, [FromForm] long bzzbid, [FromForm] long jtid)
        {
            IExporter exporter = new ExcelExporter();
            var result = await exporter.Export(@"wwwroot/download/goujian/构件库.xlsx", await _fsql.Select<GouJianZhuangBei>().Where(gjzb => gjzb.Bzzbtid == bzzbtid && gjzb.Bzzbid == bzzbid && gjzb.Jtid == jtid).ToListAsync());

            JObject data = new();
            data.Add("url", _configuration.GetValue<string>("UploadUrl") + $"/download/goujian/构件库.xlsx");
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> ImportExcel([FromForm] long bzzbtid, [FromForm] long bzzbid, [FromForm] long jtid, [FromForm] string filePath)
        {
            //filePath = @"upload/excel/构件库模板.xlsx";
            string webrootpath = _env.WebRootPath;
            FileInfo file = new FileInfo(Path.Combine(webrootpath, filePath));

            long affrows = 0;
            _fsql.Transaction(() => {
                try
                {
                    using (ExcelPackage package = new ExcelPackage(file))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
                        int rowCount = worksheet.Dimension.Rows;
                        var items = new List<Tool>();
                        for (int row = 2; row <= rowCount; row++)
                        {
                            string ssbm = "";
                            string cph = "";
                            string mc = "";
                            // 1.保障车辆(1-电源车 2-加油车) 2.保障设备 3.保障构件车辆 4.保障构件设备
                            if (bzzbtid == 3) {
                                if (bzzbid == 1) {
                                    DianYuanChe dianyuanche = _fsql.Select<DianYuanChe>().Where(dyc => dyc.Id == jtid).ToOne();
                                    ssbm = dianyuanche.Bzclwybm;
                                    cph = dianyuanche.Cph;
                                    mc = dianyuanche.Clmc;
                                }
                                if (bzzbid == 2) {
                                    JiaYouChe jiayouche = _fsql.Select<JiaYouChe>().Where(jyc => jyc.Id == jtid).ToOne();
                                    ssbm = jiayouche.Bzclwybm;
                                    cph = jiayouche.Cph;
                                    mc = jiayouche.Clmc;
                                }
                            }
                            if (bzzbtid == 4) {
                                BaoZhangSheBei baozhangshebei = _fsql.Select<BaoZhangSheBei>().Where(bzsb => bzsb.Id == jtid).ToOne();
                                ssbm = baozhangshebei.Bzsbwybm;
                                cph = "";
                                mc = baozhangshebei.Sbmc;
                            }
                            Console.WriteLine(ssbm + "-" + cph + "-" + mc);
                            //GouJianZhuangBei goujianzhuangbei = new GouJianZhuangBei { Bzzbtid = bzzbtid, Bzzbid = bzzbid, Jtid = jtid, Gjwybm = worksheet.Cells[row, 1].GetValue<string>(), Name = worksheet.Cells[row, 2].Value?.ToString() ?? "", Gjxh = worksheet.Cells[row, 3].Value?.ToString() ?? "", Gjcch = worksheet.Cells[row, 4].Value?.ToString() ?? "", Ssbm = worksheet.Cells[row, 5].Value?.ToString() ?? "", Cph = worksheet.Cells[row, 6].Value?.ToString() ?? "", Mc = worksheet.Cells[row, 7].Value?.ToString() ?? "" };
                            GouJianZhuangBei goujianzhuangbei = new GouJianZhuangBei { Bzzbtid = bzzbtid, Bzzbid = bzzbid, Jtid = jtid, Gjwybm = worksheet.Cells[row, 1].GetValue<string>(), Name = worksheet.Cells[row, 2].Value?.ToString() ?? "", Gjxh = worksheet.Cells[row, 3].Value?.ToString() ?? "", Gjcch = worksheet.Cells[row, 4].Value?.ToString() ?? "", Ssbm = ssbm, Cph = cph, Mc = mc };
                            long id = _fsql.Insert(goujianzhuangbei).ExecuteIdentity();
                            _fsql.Update<GouJianZhuangBei>(id).Set(gjzb => gjzb.Gjwybm, goujianzhuangbei.Gjwybm + String.Format("{0:D4}", id)).ExecuteAffrows();
                            affrows = row;
                        }
                    }
                }
                catch (Exception e)
                {
                    affrows = -1;
                    _logger.LogInformation("导入构件库失败：" + e.Message);
                }

            });
            if (affrows == -1)
            {
                return RenderJson(status: "failed", message: "导入构件库失败", code: -1);
            }
            return RenderJson(data: affrows);
        }
    }
}
